package com.jintoufs.web.action.category;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.common.util.JhjResponseUtil;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.domain.category.Category;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.category.CategoryService;
import com.jintoufs.util.ztree.TreeNode;
import com.jintoufs.web.action.support.JqgridPage;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.jintoufs.util.ResponseUtil.writeInfo;

/**
 * Created by xufei on 2018/1/1
 */
@Controller
@Scope("prototype")
@RequestMapping("/category")
public class CategoryAction {

    @Resource
    private CategoryService categoryService;

    /**
     * 类别信息查询
     * @param model
     * @param name
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public String list(Model model, String name) throws IOException {
        Map<String,Object> params = new HashMap<>();
        params.put("name",name);
        List<Category> list = categoryService.queryByParams(null);

        List<Object> resourceLists = categoryService.getResourceTreeList(list);
        resourceLists.remove(0);
        model.addAttribute("listEntity",list);
        return "category/list";
    }
//    /**
//     * 类别信息查询
//     * @return
//     * @throws IOException
//     */
//    @RequestMapping("/list")
//    public String list() throws IOException {
//        List<Object> resourceLists = resourceService.getResourceTreeList(resourceList);
//        resourceLists.remove(0);
//        return "category/list";
//    }
//
//    @RequestMapping("/query")
//    @ResponseBody
//    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
//        PageHelper.startPage(page, rows);
//        QueryFilters filters_ = null;
//        if (filters == null || filters.trim().isEmpty()) {
//            filters_ = new QueryFilters();
//        } else {
//            filters_ = JSON.parseObject(filters, QueryFilters.class);
//        }
//        filters_.setSidx(sidx);
//        filters_.setSord(sord);
//        List<Category> list = categoryService.getByFilter(filters_);
//        // 用PageInfo对结果进行包装
//        PageInfo pageInfo = new PageInfo(list);
//        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
//                pageInfo.getList());
//    }

    /**
     * input.do?id= 进入活动编辑与新增页面 <br>*
     * @param id    活动Id
     * @param model
     * @return
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(Integer id, Model model) {
        Category entity = null;
        Map map = new HashMap();
        // 是否为编辑保存
        Boolean isEdit = false;

        if (id != null) {
            // 修改
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", id);
            List<Category> list = categoryService.queryByParam(params);

            if (list != null && list.size() > 0) {
                entity = list.get(0);
            }
            isEdit = true;
        } else {
            // 新增
        }
        List<TreeNode> list = categoryService.getModuleTree(entity);
        model.addAttribute("ztreeNodes",JSON.toJSONString(list));
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("entity", entity);
        return "category/input";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @SystemControllerLog(description = "新增类别")
    public void save(Category category, HttpServletResponse response) throws ParseException {
        String error = null;
        if(category.getName() == null && "".equals(category.getName())){
            error = "类别名字不能为空！";
        }

        Map<String, Object>  result = categoryService.save(category);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }


    @RequestMapping("edit")
    @SystemControllerLog(description = "修改类别信息")
    public void edit(Category category, HttpServletResponse response) {
        Map<String, Object> result = categoryService.save(category);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }



    @RequestMapping("delete")
    @SystemControllerLog(description = "删除类别信息")
    public void delete(HttpServletResponse response, Category category) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            categoryService.delete(category.getId());
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DataIntegrityViolationException) {
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("该类别还在使用中，删除失败！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    /**
     * 获取详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "查看类别详细信息")
    public String getDetail(Integer id, Model model) {
        Category result = new Category();
        if (id != null && id != 0) {
            result = categoryService.getById(id);
        }
        model.addAttribute("entity", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "类别详细信息");
        return "category/detail";
    }
}
